import os

# 1, 导入celery类,和配置文件
from celery import Celery
from . import config
from PMSP.utils.yuntongxun.sms import CCP
from django.core.mail import send_mail
from django.conf import settings

# 2， 设置celery运行的环境变量
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'PMSP.settings.dev')

# 3， 创建celery对象
app = Celery('PMSP')

# 4, 加载配置
app.config_from_object(config, namespace='CELERY')

# 5，自动注册任务
app.autodiscover_tasks()

# 6，使用app装饰任务（异步任务）
@app.task(bind=True)
def debug_task(self):
    import time
    time.sleep(3)
    print(f'Request: {self.request!r}')

# 7, 封装短信发送的异步任务
@app.task(bind=True)
def send_sms_code(self,mobile,sms_code):
    import time
    time.sleep(5)
    ccp = CCP()
    ccp.send_template_sms(mobile, [sms_code, 5], 1)

# 8, 封装邮件发送任务
@app.task(bind=True)
def send_verify_url(self,email,html_msg):
    send_mail(
        subject='PMSP Active Email',
        message="",
        from_email=settings.EMAIL_HOST_USER,
        recipient_list=[email],
        html_message=html_msg
    )

# 启动Celery服务， celery -A PMSP.utils.celery_task.celery worker -l INFO --logfile PMSP/utils/celery_task/celery.log
# 调用异步任务，debug_task.delay()